import { useEffect, useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Modal, message, Form, Input } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import {
  storegroupSearch,
  storegroupEdit,
  storegroupRefresh,
  storegroupStoreList,
  storegroupStoreEdit,
} from '@/services/storegroup';
import StorageManager from '@/utils/StorageManager';

import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const { confirm } = Modal;

const StoregroupList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modalForm] = Form.useForm();
  const [modalStoreForm] = Form.useForm();
  const storesWatch = Form.useWatch('stores', modalStoreForm);
  const [valueEnumActivityId, setValueEnumActivityId] = useState({});
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelVisible, setModelVisible] = useState<boolean>(false);
  const [modelStoreVisible, setModelStoreVisible] = useState<boolean>(false);

  // 提交
  const handleOperate = async (record: API.StoregroupListItem, type: string) => {
    if (type === '修改') {
      modalForm.setFieldsValue({ ...record });
      setModelVisible(true);
      return;
    }

    if (type === '门店') {
      modalStoreForm.setFieldsValue({ ...record });
      const { code, data } = await storegroupStoreList({ storegroup: record.storegroup });
      if (code === 200 && data) {
        modalStoreForm.setFieldValue('stores', data.stores || '');
      }
      setModelStoreVisible(true);
      return;
    }

    confirm({
      content: `确认${type} 餐厅组：${record.storegroupname}？`,
      async onOk() {
        if (type === '刷新') {
          const { code, data } = await storegroupRefresh({ storegroup: record.storegroup });
          if (code === 200 && data) {
            message.success('刷新成功');
            actionRef?.current?.reloadAndRest?.();
          } else {
            message.error('刷新失败');
          }
        }
      },
      onCancel() {},
    });
  };

  useEffect(() => {
    const eunmList: any = StorageManager.getLocalStorageSync('eunmList');
    const obj: any = {};
    eunmList?.OptionsPlaceBrandList.forEach((item: any) => {
      obj[item.value] = {
        text: item.label,
      };
    });
    setValueEnumActivityId({
      // ALL: { text: 'ALL' },
      ...obj,
    });
  }, []);

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '餐厅组名',
      dataIndex: 'storegroupname',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
      // initialValue: '123',
    },
    {
      title: '品牌ID',
      dataIndex: 'brandid',
      hideInTable: true,
      fieldProps: {
        placeholder: '请选择',
      },
      valueEnum: valueEnumActivityId,
      // initialValue: 'ALL',
    },
    // 表格
    {
      title: '品牌ID',
      dataIndex: 'brandid',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '餐厅组',
      dataIndex: 'storegroup',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '餐厅组名称',
      dataIndex: 'storegroupname',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 200,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => handleOperate(record, '修改')}>修改</a>&nbsp;&nbsp;
            <a onClick={() => handleOperate(record, '刷新')}>刷新</a>&nbsp;&nbsp;
            <a onClick={() => handleOperate(record, '门店')}>门店</a>&nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.StoregroupSearchInfo = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await storegroupSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleOK = () => {
    modalForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await storegroupEdit({
        ...values,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalForm.resetFields();
        setModelVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const handleCancel = () => {
    setModelVisible(false);
    modalForm.resetFields();
  };

  const handleStoreOK = () => {
    modalStoreForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await storegroupStoreEdit({
        ...values,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalStoreForm.resetFields();
        setModelStoreVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const handleStoreCancel = () => {
    setModelStoreVisible(false);
    modalStoreForm.resetFields();
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.StoregroupListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="修改"
          width={520}
          open={modelVisible}
          onOk={handleOK}
          onCancel={handleCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalForm}
            initialValues={{
              id: '',
              brandid: '',
              storegroup: '',
              storegroupname: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="品牌ID"
              name="brandid"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="brandid" />
            </Form.Item>
            <Form.Item
              label="餐厅组"
              name="storegroup"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="storegroup" disabled={true} />
            </Form.Item>
            <Form.Item
              label="餐厅组名称"
              name="storegroupname"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="storegroupname" />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="门店信息"
          width={520}
          open={modelStoreVisible}
          onOk={handleStoreOK}
          onCancel={handleStoreCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalStoreForm}
            initialValues={{
              stores: '',
              storegroup: '',
              storegroupname: '',
            }}
          >
            <Form.Item label="餐厅组" name="storegroup">
              <Input disabled={true} placeholder="storegroup" />
            </Form.Item>
            <Form.Item label="餐厅组名称" name="storegroupname">
              <Input disabled={true} placeholder="storegroupname" />
            </Form.Item>
            <Form.Item
              label="门店列表"
              name="stores"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input.TextArea rows={4} placeholder="门店列表，逗号隔开" />
            </Form.Item>
            <div style={{ textAlign: 'right', color: 'red', marginTop: -20 }}>
              共{storesWatch && storesWatch.length > 0 ? (storesWatch || '').split(',').length : 0}
              家餐厅
            </div>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default StoregroupList;
